package cz.gillan.housecosts.sql;

import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import cz.gillan.housecosts.data.Gauge;
import cz.gillan.housecosts.data.StateImpl;

public class StateDbAdapter extends AbstractDbAdapter {
	public static final String KEY_ROWID = "_id";
	public static final String KEY_GAUGEID = "gaugeid";
	public static final String KEY_STATE = "state";  
	public static final String KEY_DATE = "date";
	public static final String KEY_COMMENT = "comment";
	public static final String DB_TABLE = "state";
	private static final String[] ALL_COLUMNS = new String[]{ KEY_ROWID , KEY_GAUGEID, KEY_STATE, KEY_DATE, KEY_COMMENT };
	
	public StateDbAdapter(Context context) {
		super(context);
	}
	
	public Long createNewState(Long gaugeId, Long date, Double value, String comment) {
		ContentValues initialValues = createContentValues(gaugeId, date, value, comment);
		return  getDatabase().insert(DB_TABLE, null, initialValues);
	}
	
	public boolean updateState(Long rowId, Long date, Double value, String comment) {
		ContentValues initialValues = createContentValues(null, date, value, comment);
		return getDatabase().update(DB_TABLE, initialValues, KEY_ROWID + "=" + rowId, null) > 0;
	}
	
	public boolean deleteState(StateImpl state) {
		return getDatabase().delete(DB_TABLE, KEY_ROWID + "=" + state.getId(), null) > 0;
	}
	
	public Cursor fetchState(long rowId) {
		Cursor cursor = getDatabase().query(true, DB_TABLE, ALL_COLUMNS, KEY_ROWID + "=" + rowId, null, null, null, null, null);
		if (cursor != null) {
			cursor.moveToFirst();
		}
		return cursor;
	}
	
	public Cursor fetchAllStates(long gaugeId) {
		Cursor cursor = getDatabase().query(true, DB_TABLE, ALL_COLUMNS, KEY_GAUGEID + "=" + gaugeId, null, null, null, KEY_DATE + " DESC", null);
		if (cursor != null) {
			cursor.moveToFirst();
		}
		return cursor;
	}
	
	private ContentValues createContentValues(Long gaugeId, Long date, Double value, String comment) {
		ContentValues values = new ContentValues();
		if (gaugeId != null) {
			values.put(KEY_GAUGEID, gaugeId);
		}
		values.put(KEY_STATE, value);
		values.put(KEY_DATE, date);
		values.put(KEY_COMMENT, comment);
		return values;
	}
}
 